﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace SuperTimeSync
{
    public static class GetTime
    {
        public static string GetJson(string url)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        public static string GetTimeJsonString(string url, string key)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(GetJson(url));
            if (key == "t")
            {
                object v = json["data"];
                json = (Dictionary<string, object>)v;
            }
            return json[key].ToString();
        }

        public static DateTime GetDt(string url, string key)
        {
            string TimeString = GetTimeJsonString(url, key);
            long time = long.Parse(TimeString) / 1000;   //转换成秒
            int stime = (int)(long.Parse(TimeString) - (long.Parse(TimeString) / 1000) * 1000);  //计算毫秒部分
            DateTime dt = new DateTime(1970, 1, 1).AddSeconds(time);
            DateTime dt1 = dt.AddHours(8).AddMilliseconds(stime);    //+8转为中国时区
            return dt1;
        }

        public static string DTime(int sindex, ref DateTime dt)
        {
            if (sindex == 0)
            {
                dt = GetDt(ApiData.taobaoApi[0], ApiData.taobaoApi[1]);
                return dt.ToString("yyyy-MM-dd HH-mm-ss fff");
            }
            if (sindex == 1)
            {
                dt = GetDt(ApiData.pinduoduoApi[0], ApiData.pinduoduoApi[1]);
                return dt.ToString("yyyy-MM-dd HH-mm-ss fff");
            }
            else
            {
                dt = new DateTime();
                return "";
            }
        }
    }
}